<?php
namespace app\api\controller;

class CompanyIncomeExpenseCate extends Permission
{
    public function getTreeList()
    {
        $list = db('CompanyIncomeExpenseCate')
            ->order('pid ASC, id ASC')
            ->select();

        // 按 pid 分组
        $group = [];
        foreach ($list as $v) {
            $group[$v['pid']][] = $v;
        }

        // 递归生成平面树，带缩进
        function buildFlatTree($parentId, &$group, &$result, $level = 0) {
            if (!isset($group[$parentId])) return;
            foreach ($group[$parentId] as $item) {
                // 在 title 前加上缩进符号
                $item['title'] = str_repeat('----', $level) . $item['title'];
                $result[] = $item;
                buildFlatTree($item['id'], $group, $result, $level + 1);
            }
        }

        $result = [];
        buildFlatTree(0, $group, $result);

        // 输出
        $this->resSuc($result);
    }
    public function getList()
    {
        $page = isset($this->input_data['page']) ? $this->input_data['page'] : 1;
        $limit = isset($this->input_data['limit']) ? $this->input_data['limit'] : 9999;

        $map = [];
        if($this->post('pid') != '') $map['pid'] = $this->post('pid');
        
        $total = db('CompanyIncomeExpenseCate')->where($map)->count();
        $row = db('CompanyIncomeExpenseCate')->where($map)->page($page,$limit)->select();
        $list = [];

        if($this->post('pid') == 0)
        {
            $list[] = [
                'id' => 0,
                'pid' => 0,
                'title' => '顶级分类'
            ];
        }

        foreach ($row as $v) {
            // $v['rules'] = explode(',',$v['rules']);
            $list[] = $v;
        }
        
        
        $data = array(
            'total' => $total,
            'list' => $list     
        );
        $this->resSuc($data);
    }
    
    public function del()
    {
        $map = [
            'cate_id' => $this->post('id')
        ];
        if(db('CompanyIncomeExpense')->where($map)->find()) $this->resErr('此分类下还有数据，无法删除');
        db('CompanyIncomeExpenseCate')->delete($this->input_data['id']);

        $this->resSuc('删除成功');
        
        
    }

    public function update()
    {
        $data['title'] = $this->input_data['title'];
        $data['pid'] = $this->input_data['pid'];
        
        
        if($this->input_data['id'] > 0)
        {
            $data['id'] = $this->input_data['id'];
            db('CompanyIncomeExpenseCate')->update($data);
        }
        else
        {
            $id = db('CompanyIncomeExpenseCate')->insertGetId($data);
        }

        $this->resSuc('操作成功');
    }
    
}
